<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Constants\ContactTaskCenterTyperConstants;
use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Dto\ContactTcContentDto;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChOpSchemeMapper;
use App\CustHub\Mapper\ChOpSchemeRobotMapper;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChSmartTag;
use App\CustHub\Traits\OpSchemeTrait;
use Hyperf\Collection\Collection;
use Hyperf\Collection\Enumerable;
use Hyperf\Database\Model\Builder;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;

/**
 * 关键词标签
 */
class ChKeywordTagSchemeService extends AbstractService
{
    use OpSchemeTrait;

    public $mapper;

    protected $type = OpSchemeTypeConstants::KEYWORD_TAG;

    #[Inject]
    protected ChOpSchemeRobotMapper $schemeRobotMapper;

    #[Inject]
    protected ChContactMapper $contactMapper;

    public function __construct(ChOpSchemeMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        $name = data_get($params, 'name');
        $keyword = data_get($params, 'keyword');
        $corpTagIds =  data_get($params, 'corp_tag_ids');
        $smartTagIds = data_get($params, 'smart_tag_ids');
        $corpId = data_get($params, 'corp_id');

        $query->with(['corp' => function ($query) {
            $query->select(['id','corp_name']);
        }]);

        if(!empty($corpId)){
            $query->where('corp_id',$corpId);
        }

        if(!empty($name)){
            $query->where('name','like',$name.'%');
        }

        if(!empty($keyword)){
            $query->whereRaw("JSON_SEARCH(cfg, 'one', '%{$keyword}%', NULL, '$.keywords') IS NOT NULL");
        }

        if(!empty($corpTagIds)){
            $query->whereRaw("JSON_CONTAINS(`cfg`, '{$corpTagIds}', '$.corp_tag_ids')");
        }

        if(!empty($smartTagIds)){
            $query->whereRaw("JSON_CONTAINS(`cfg`, '{$smartTagIds}', '$.smart_tag_ids')");
        }

        return $query;
    }

    public function handlePageItems(array $items,array $params): Enumerable|Collection
    {
        $items = collect($items);
        $corpTagIds = $items->flatMap(function ($item){
            return $item['cfg']['corp_tag_ids'] ?? [];
        })->unique()->toArray();

        $smartTagIds = $items->flatMap(function ($item){
            return $item['cfg']['smart_tag_ids'] ?? [];
        })->unique()->toArray();

        //查询企业标签
        $corpTagList = ChCorpTag::query()
            ->whereIn('id',$corpTagIds)
            ->pluck('name','id')
            ->toArray();

        //查询智能标签
        $smartTagList = ChSmartTag::query()
            ->whereIn('id',$smartTagIds)
            ->pluck('name','id')
            ->toArray();

        $items = $items->map(function ($item) use ($corpTagList,$smartTagList){
            $cfg = $item['cfg'];
            if(!empty($cfg['corp_tag_ids'])){
                foreach ($cfg['corp_tag_ids'] as $corpTagId){
                    if(isset($corpTagList[$corpTagId])){
                        $cfg['corp_tags'][] = [
                            'id' => $corpTagId,
                            'name' => $corpTagList[$corpTagId]
                        ];
                    }
                }
            }

            if(!empty($cfg['smart_tag_ids'])){
                foreach ($cfg['smart_tag_ids'] as $corpTagId){
                    if(isset($smartTagList[$corpTagId])){
                        $cfg['smart_tags'][] = [
                            'id' => $corpTagId,
                            'name' => $smartTagList[$corpTagId]
                        ];
                    }
                }
            }
            $item['cfg'] = $cfg;
            return $item;
        });
        return $items;
    }

    public function triggerScheme(array $data,ChRobot $robot)
    {
        //发送方
        $sender = (string)$data['sender'];

        $userId = $robot->user_id == $sender ? $data['receiver']: $sender;

        $contact = $this->contactMapper->findByRobotIdAndUserId($robot->id,$userId);
        if(empty($contact)){
            return;
        }

        //获取
        $robotSchemeList = $this->schemeRobotMapper->findRobotScheme($robot['id'],$this->type);
        if(empty($robotSchemeList)){
            return;
        }

        $allCrpTagIds = [];
        $allSmartTagIds = [];
        foreach ($robotSchemeList as $robotScheme){
            $scheme = $robotScheme->scheme;
            if(empty($scheme)){
                continue;
            }

            $config = $scheme->cfg;

            if($config['trigger_obj'] == 0 && $robot->user_id == $sender){
                //仅客户触发
                continue;
            }

            $keywords = $config['keywords'];
            $matchType = data_get($config,'match_type',0);
            if(!checkKeywords($keywords,$data['content'],$config['trigger_type'],$matchType)){
                continue;
            }

            //满足条件给用户打标签
            //企微标签
            $corpTagIds = data_get($config,'corp_tag_ids',[]);
            $allCrpTagIds = array_merge($allCrpTagIds,$corpTagIds);
            //客户标签
            $smartTagIds = data_get($config,'smart_tag_ids',[]);
            $allSmartTagIds = array_merge($allSmartTagIds,$smartTagIds);
        }


        if(!empty($allCrpTagIds)){
            //企业标签
            $content = new ContactTcContentDto();
            $content->setContactIds([$contact->id]);
            $content->setTagIds(array_unique($allCrpTagIds));
            container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::PUT_ON_CORP_TAG,$content);
        }

        if(!empty($allSmartTagIds)){
            //智能标签
            $content = new ContactTcContentDto();
            $content->setContactIds([$contact->id]);
            $content->setTagIds(array_unique($allSmartTagIds));
            container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::PUT_ON_SMART_TAG,$content);
        }

    }
}